import Auth from './utils.js';

document.addEventListener('DOMContentLoaded', function () {
    // 获取显示信息按钮并添加点击事件
    const infoBtn = document.querySelector('.info-btn');
    infoBtn.addEventListener('click', function () {
        // 获取token
        const token = Auth.getToken();
        // 设置请求头，添加token
        const headers = {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${token}`
        };

        // 首先调用获取当前用户信息的接口
        fetch('http://localhost:9090/user/userInfo', {
            method: 'GET',
            headers: headers
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.json();
            })
            .then(data => {
                if (data.success) {
                    // 存储获取到的用户信息
                    const userInfo = data;

                    // 构建请求体，准备发送到完善个人信息接口
                    const updateData = {
                        userId: userInfo.userId,
                        userName: userInfo.userName,
                        email: userInfo.email,
                        createTime: userInfo.createTime,
                        updateTime: userInfo.updateTime,
                        userPic: userInfo.userPic
                    };

                    // 设置请求头，添加token
                    const updateHeaders = {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${token}`
                    };

                    // 调用完善个人信息接口
                    return fetch('http://localhost:9090/user/update', {
                        method: 'PUT',
                        headers: updateHeaders,
                        body: JSON.stringify(updateData)
                    });
                }
                throw new Error('Failed to fetch user info');
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.json();
            })
            .then(data => {
                if (data.success) {
                    // 更新页面上的用户信息
                    document.getElementById('profileImage').src = data.userPic || 'https://profile-avatar.csdnimg.cn/default.jpg';
                    document.getElementById('username').textContent = data.userName;
                    document.getElementById('userId').textContent = data.userId;
                    document.getElementById('email').textContent = data.email;
                    document.getElementById('createTime').textContent = data.createTime;
                    document.getElementById('updateTime').textContent = data.updateTime;
                    alert('用户信息更新成功');
                } else {
                    alert('更新失败: ' + data.message);
                }
            })
            .catch(error => {
                alert('请求出错: ' + error.message);
            });
    });

    // 头像更换操作
    const profileImage = document.getElementById('profileImage');
    profileImage.addEventListener('click', function () {
        const fileInput = document.createElement('input');
        fileInput.type = 'file';
        fileInput.accept = 'image/*';
        fileInput.onchange = function (e) {
            const file = e.target.files[0];
            const formData = new FormData();
            formData.append('file', file);
            // 获取token
            const token = Auth.getToken();
            // 设置请求头，添加token
            const headers = {
                'Authorization': `Bearer ${token}`
            };
            fetch('http://localhost:9090/user/updateAvatar', {
                method: 'PATCH',
                headers: headers,
                body: formData
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Network response was not ok');
                    }
                    return response.json();
                })
                .then(data => {
                    if (data.success) {
                        profileImage.src = URL.createObjectURL(file);
                        alert('头像更新成功');
                    } else {
                        alert('更新失败: ' + data.message);
                    }
                })
                .catch(error => {
                    alert('请求出错: ' + error.message);
                });
        };
        fileInput.click();
    });

    // 修改密码操作
    const changePasswordBtn = document.querySelector('.change-password-btn');
    changePasswordBtn.addEventListener('click', function () {
        const oldPassword = prompt("请输入旧密码：");
        const newPassword = prompt("请输入新密码：");
        const rePassword = prompt("请确认新密码：");

        if (oldPassword && newPassword && rePassword && newPassword === rePassword) {
            const pwdData = {
                old_pwd: oldPassword,
                new_pwd: newPassword,
                re_pwd: rePassword
            };
            // 获取token
            const token = Auth.getToken();
            // 设置请求头，添加token
            const headers = {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${token}`
            };

            fetch('http://localhost:9090/user/updatePwd', {
                method: 'PATCH',
                headers: headers,
                body: JSON.stringify(pwdData)
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Network response was not ok');
                    }
                    return response.json();
                })
                .then(data => {
                    if (data.success) {
                        alert('密码修改成功');
                    } else {
                        alert('修改失败: ' + data.message);
                    }
                })
                .catch(error => {
                    alert('请求出错: ' + error.message);
                });
        } else {
            alert('密码不匹配或未输入');
        }
    });
});